package com.aboo.jdk7;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author louan
 * @date 2024-06-29
 * @description Java7提供的一个用于并行执行任务的Fork/Join框架，是一个把大任务分割成若干个小任务，最终汇总每个小任务结果后得到大任务结果的框架。
 */
public class CountTask extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 5;
    private int start;
    private int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= THRESHOLD;
        // 任务小就直接计算
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            // 如果任务大于廓值，则分割成2个子任务计算
            int middle = (start + end) / 2;
            CountTask countTask1 = new CountTask(start, middle);
            CountTask countTask2 = new CountTask(middle + 1, end);
            // 执行子任务
            countTask1.fork();
            countTask2.fork();
            // 等待子任务执行完，得到执行结果
            int leftResult = countTask1.join();
            int rightResult = countTask2.join();
            // 合并子任务结果
            sum = leftResult + rightResult;
        }
        return sum;
    }
    public static void main(String[] args) throws Exception {
        ForkJoinPool pool = new ForkJoinPool();
        CountTask task = new CountTask(1, 10);
        Future<Integer> future = pool.submit(task);
        System.out.println(future.get());
    }
}